﻿using GDGeek;
using MrPP.Common;
using MrPP.iot;
using MrPP.ProgramPlatform;
using MrPP.Restful;
using MrPP.SocketSystem;
using MrPP.Tracking;
using MrPP.UX;
using System;
using System.Collections.Generic;
using UnityEngine;
using Heartbeat = MrPP.iot.Heartbeat;

namespace MrPP.SerriedCabinet
{
    public class ResultData {
        public long time;
        public bool succeed;
    }
    public class WindowProcess : GDGeek.Singleton<WindowProcess>{

        [SerializeField]
        WindowFactory _factory;
        // [SerializeField]
        // private VuforiaMark.Mark _mark = VuforiaMark.Mark.Mark8;


        //  [SerializeField]
        //  private Transform _anchor;
#if UNITY_EDITOR

        [SerializeField]
        private string _stateName;
#endif
        [SerializeField]
        private WindowModel _manager;

        private FSM fsm_ = new FSM();

        public void onInitialStatus(InitialStatusFactory.Data data)
        {
            this.fsm_.post("InitialStatus");
        }

        internal void onOpen(int item2)
        {

            openId_ = item2;

            fsm_.post("open_id");
        }

        /*
public void onAreaColumnConfiguration(AreaColumnConfigurationFactory.Data data)
{
   this.fsm_.post("AreaColumnConfiguration");
}*/
        /*
        public void testScanning()
        {
            StartWindow.Data data = new StartWindow.Data();
            data.url = "http://localhost:3000/geek/1/1";

            url_ = data.url;
            anchor_ = this._anchor;
            BoxRoot.Instance.mount(anchor_);
            this.fsm_.post("scanning");
        }*/
        void Start()
        {


            InitialStatusFactory.Instance.onRecevie += onInitialStatus;


            fsm_.addState("start", start());
            fsm_.addState("init", init(), "start");
            fsm_.addState("scanning", scanning(), "start");
            fsm_.addState("setup", setup(), "start");
            fsm_.addState("initialStatus", initialStatus(), "start");



            fsm_.addState("main", main());
            fsm_.addState("run", run(), "main");
            fsm_.addState("ventilate", ventilate(), "main");
            fsm_.addState("close", close(), "main");
            fsm_.addState("stop", stop(), "main");
            fsm_.addState("selected", selected(), "main");
            fsm_.addState("open", open(), "main");
            fsm_.addState("open_id", open_id(), "main");

            fsm_.init("init");
         
        }
        private int openId_ = -1;
        private StateBase open_id()
        {
            State ts = TaskState.Create(delegate {

                return BoxOperation.Instance.open(openId_);


            }, this.fsm_, "run");
            return ts;
        }

        private StateBase start()
        {
            State state = new State();
            state.onStart += delegate
            {
                _manager.state = WindowModel.State.Start;
          
            };
            state.onOver += delegate
            {

            };
            return state;
        }

        private StateBase init()
        {
            State state = TaskState.Create(delegate {
                _factory.create();
                Task task = new Task();
                return task;
            }, fsm_, "scanning");
            return state;
        }

        private StateBase scanning()
        {
            State state = new State();
            state.onStart += delegate
            {
           
            };

            state.addAction("scanning", delegate
            {
                if (!string.IsNullOrEmpty(url_) && anchor_ != null)
                {
                    return "setup";
                }
                return "";
            });
            state.onOver += delegate
            {
                UrlManager.Instance.api = url_;
            };
            return state;
        }

        private StateBase setup()
        {
            State state = TaskState.Create(delegate {
                var op = Restful.RestfulManager.Instance.options(Restful.RestfulManager.Uri("setup"));
                Task task = Restful.RestfulManager.Instance.getTask<Setup.Data>(op, delegate (Setup.Data data)
                {
              
                    Heartbeat.Instance.open();
                    CabinetGroup.Instance.data = data;

                });


                return task;
            }, fsm_, "initialStatus");

            state.onStart += delegate
            {
                var op = Restful.RestfulManager.Instance.options(Restful.RestfulManager.Uri("areaColumnConfiguration"));
                Restful.RestfulManager.Instance.get<ResultData>(op, delegate (ResultData result)
                {
                    Debug.Log(result);
                });

            };
            return state;

        }
        /*
        private StateBase areaColumnConfiguration()
        {
            State state = new State();
            state.onStart += delegate
            {
                var op = Restful.RestfulManager.Instance.options(Restful.RestfulManager.Uri("areaColumnConfiguration"));
                Restful.RestfulManager.Instance.get<ResultData>(op, delegate (ResultData result)
                {
                    Debug.Log(result);
                });

            };
            state.addAction("AreaColumnConfiguration", "initialStatus");
            return state;
        }
        */
        private StateBase initialStatus()
        {
            State state = new State();
            state.onStart += delegate
            {
                var op = Restful.RestfulManager.Instance.options(Restful.RestfulManager.Uri("initialStatus"));
                Restful.RestfulManager.Instance.get<ResultData>(op, delegate (ResultData result)
                {
                    Debug.Log(result.time);
                });

            };
            state.addAction("InitialStatus", "run");
            return state;
        }


        private StateBase main()
        {

            State state = new State();
            state.onStart += delegate
            {

                _manager.state = WindowModel.State.Main;
              //  _manager._main.gameObject.SetActive(true);
            };
            state.onOver += delegate
            {

              //  _manager.state = WindowModel.State.None;
              //  _manager._main.gameObject.SetActive(false);
            };
            return state;
         
        }

      

       

      
        private StateBase run()
        {
            State state = new State();
            state.onStart += delegate
            {
                _manager.state = WindowModel.State.Main;
             
            };

            state.addAction("select", "selected");
            state.addAction("stop", "stop");
            state.addAction("close", "close");
            state.addAction("open", "open");
            state.addAction("open_id", "open_id");
            state.addAction("ventilate", "ventilate");

            return state;  
        }

     
      
        private string url_;
        private Transform anchor_ = null;
        public void doQrcode(string url)
        {
            //  Debug.Log(url);
          //dirui  url = "http://10.109.1.245:3000/geek/A/01/";
            url_ = url;
            Debug.LogError(url);
            fsm_.post("scanning");
        }
        public void doVuforia(Transform anchor)
        {
          //  Debug.LogError(anchor.name);
            anchor_ = anchor;
           
            fsm_.post("scanning");
        }
       
      

        private StateBase stop()
        {

            State ts = TaskState.Create(delegate {


                return BoxOperation.Instance.stop();

            }, this.fsm_, "run");
            return ts;
        }

        private StateBase open()
        {
           
            State ts = TaskState.Create(delegate {

                return BoxOperation.Instance.open(selected_);
      

            }, this.fsm_, "run");
            return ts;

        }

        private StateBase close()
        {
            State ts = TaskState.Create(delegate {
                return BoxOperation.Instance.close();
  
            }, this.fsm_, "run");
            return ts;
        }
        private StateBase ventilate()
        {
            State ts = TaskState.Create(delegate {

                return BoxOperation.Instance.ventilate();
              

            }, this.fsm_, "run");
            return ts;
        }

        RespTheInitialStatus.Data _status;
        private StateBase status()
        {
            DataTask<RespTheInitialStatus.Data> dt = null;
            State ts = TaskState.Create(delegate {
                dt = SerriedCabinetManager.Instance.initialStatus();

                return dt;
            }, this.fsm_, delegate {
                Debug.Log(dt.data);
                if (dt.data != null)
                {
                    _status = dt.data;
                    return "normal";
                }
                else
                {
                    return "link";
                }
            });
            return ts;
        }

      
        private StateBase input()
        {
            State state = new State();
            state.onStart += delegate
            {

                _manager.state = WindowModel.State.Start;
               // _manager._start.gameObject.SetActive(true);
            };
            state.onOver += delegate
            {
           //    _manager.state = WindowModel.State.None;
              //  _manager._start.gameObject.SetActive(false);
            };
            return state;
        }
        RespAreaColumnConfiguration.Data _setup;
        private StateBase ask()
        {
            DataTask<RespAreaColumnConfiguration.Data> dt = null;
            State ts = TaskState.Create(delegate {
                dt = SerriedCabinetManager.Instance.areaColumnTask();

                return dt;
            }, this.fsm_, delegate {
                Debug.Log(dt.data);
                if (dt.data != null)
                {
                    _setup = dt.data;
                    return "status";
                }
                else
                {
                    return "link";
                }
            });
            return ts;
        }
    
        public void onVentilate()
        {

            fsm_.post("ventilate");
        }

        public void onStop()
        {

            fsm_.post("stop");
        }
        public void doClose()
        {

            fsm_.post("close");
        }
        public void onOpen()
        {
            fsm_.post("open");
        }

        public void select(Button button)
        {
            onSelect(button.gameObject.AskComponent<IntId>().id);

        }
        public void onSelect(int id)
        {
            Debug.Log(id);
            if (id == CabinetGroup.Instance.data.cabinets.fix)
            {
                return;
            }
            if (id >= CabinetGroup.Instance.count || id < 0)
            {
                return;
            }
            selected_ = id;
            fsm_.post("select");
        }
        private StateBase selected()
        {
            State state = new State();
           // Button button = null;
            state.onStart += delegate
            {

                _manager.selected = selected_;
               // _manager._operation.gameObject.SetActive(true);
              //  button = _manager._buttons.getButton(selected_);
               // _manager.state = Button.State.Selected; ;
               // button.refresh();
            };
          

            state.addAction("select", "selected");
            state.addAction("close", "close");
            state.addAction("ventilate", "ventilate");
            state.addAction("open", "open");
            state.addAction("stop", "stop");

            state.onOver += delegate
            {

                //button.state = Button.State.Enabled;
                //button.refresh();

                _manager.selected = -1;
                //_manager._operation.gameObject.SetActive(false);
            };
            return state;
        }
     
        private int selected_ = -1;

        private StateBase normal()
        {
            State state = new State();

            state.addAction("select", "selected");
            state.addAction("close", "close");
            state.addAction("ventilate", "ventilate");
            state.addAction("open", "open");
            state.addAction("stop", "stop");
            return state;
        }
      
        public void load()
        {
            this.fsm_.post("load");
        }


#if UNITY_EDITOR
        void Update() {
            _stateName = fsm_.getCurrSubState().name;
        }
#endif
           

    }
}